const express = require('express');
const router = express.Router();
const mongoose = require('../../db/db.js');
const deviceSchema = require('../../db/cloudControl/deviceSchema');

router.get('/pageList', async (req, res) => {
	try {
		const { userName, userId } = req.session;
		const { page, limit, deviceName, taskStatus, groupId } = req.query;
		const deviceMod = mongoose.model(`device_${userName}`, deviceSchema);

		let search = {};
		if (deviceName) search.deviceName = new RegExp(deviceName, 'i');
		if (taskStatus) search.taskStatus = taskStatus;
		if(groupId == 'null') search.groupId = null;
		
		const count = await deviceMod.countDocuments(search);
		const docs = await deviceMod
			.find(search)
			.skip((page - 1) * limit)
			.limit(parseInt(limit) || 20)
			.exec();
		res.json({
			code: 0,
			msg: '查询成功',
			count: count,
			data: docs,
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

router.post('/del',async (req, res)=>{
	try {
		const { userName, userId } = req.session;
		const { deviceIds } = req.body;
		const deviceMod = mongoose.model(`device_${userName}`, deviceSchema);
		const result = await deviceMod.deleteMany({_id:{$in:deviceIds}}).exec();
		res.json({
			code: 0,
			msg: '删除成功',
			data: result
		})
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
})

router.post('/inGroup', async (req, res) => {
	try {
		const { userName, userId } = req.session;
		const { deviceIds, groupId } = req.body;

		const deviceMod = mongoose.model(`device_${userName}`, deviceSchema);
		const result = await deviceMod.updateMany({_id:{$in:deviceIds}},{$set:{groupId}}).exec();

		res.json({
			code: 0,
			msg: '添加成功',
			data: result
		})
	}catch(error){
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

router.get('/pageListByGroupId', async (req, res) => {
	try {
		const { userName, userId } = req.session;
		const { groupId,deviceName } = req.query;
		const deviceMod = mongoose.model(`device_${userName}`, deviceSchema);
		let search = {};
		if (deviceName) search.deviceName = new RegExp(deviceName, 'i');
		if (groupId) search.groupId = groupId;
		const docs = await deviceMod.find(search).exec();
		const count = await deviceMod.countDocuments(search);
		res.json({
			code: 0,
			count: count,
			msg: '查询成功',
			data: docs,
		});
	}catch(error){
		res.json({
			code: -1,
			msg: error.message,
		});
	}
})


module.exports = router;